package com.jaydenxiao.common.commonutils;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.text.TextUtils;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okio.ByteString;

/**
 * Created by admin on 2016-08-17.
 */
public class StringTool {


    private static final String TAG = StringTool.class.getSimpleName();

    public static String getUTF8String(String s){

        if (s==null){
            s="";
        }else {
            try {
                s = URLEncoder.encode(s,"UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return s;
    }

    public static double getLongitude(String s){
        s=s.substring(0,s.indexOf(','));
        return Double.parseDouble(s);
    }

    public static double getLatitude(String s){
        s=s.substring(s.indexOf(',')+1);
        return Double.parseDouble(s);
    }

    public static double getSixDouble(Double d){
        DecimalFormat df=new DecimalFormat();
        //保留几位小数
        df.setMaximumFractionDigits(6);
        //模式  四舍五入
        df.setRoundingMode(RoundingMode.UP);
        return Double.parseDouble(df.format(d));
    }


    public static boolean judgeStringValue(String s){
        if (s!=null&&!s.equals("")){
            return true;
        }else {
            return false;
        }
    }



    public static String timeToString(long time){
        SimpleDateFormat format=new SimpleDateFormat("HH:mm:ss");
        format.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
        return format.format(time);
    }



    public static String secondToTime(long time){
        String hour="";
        String minute="";
        String second="";
        int hourInt= (int) (time/3600);
        if (hourInt<10){
            hour="0"+hourInt;
        }else {
            hour=String.valueOf(hourInt);
        }
        int second1= (int) (time%3600);
        int minuteInt=second1/60;
        if (minuteInt<10){
            minute="0"+minuteInt;
        }else {
            minute=String.valueOf(minuteInt);
        }
        int second2=second1%60;
        if (second2<10){
            second="0"+second2;
        }else {
            second=String.valueOf(second2);
        }
        return hour+":"+minute+":"+second;
    }





    // Bean --> Map     前面加字段
    public static Map<String, String> transBean2Map(String writSort,Object javaBean, String[] ignores) {

        if (javaBean == null) {
            return null;
        }
        Map<String, String> map = new HashMap<String, String>();
        String key = "";
        String value = "";



        Method[] caseInfoMethods = javaBean.getClass().getDeclaredMethods();
        for (int i = 0; i < caseInfoMethods.length; i++) {
            if (caseInfoMethods[i].getName().startsWith("get")) {
                key = caseInfoMethods[i].getName().substring(3);
                key=writSort+Character.toLowerCase(key.charAt(0))+key.substring(1);
//                key=Character.toLowerCase(key.charAt(0))+key.substring(1);
                if (key.equals("id")||key.equals("tableId")){
                    continue;
                }
                try {
                    value = (String) caseInfoMethods[i].invoke(javaBean, (Object[]) null);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
                //忽略掉不需要的属性
                boolean isIgnore=true;
                for (String s:ignores){
                    if (key.equals(s)){
                        isIgnore=true;
                        break;
                    }else {
                        isIgnore=false;
                    }
                }
                if (isIgnore==false){
                    map.put(key,value==null?"":value);
//                        map.putString(key,value==null? "fh":"haodeddde");
                }
            }
        }
        return map;
    }



/*

    // Bean --> Map     前面加字段
    public static Map<String, RequestBody> transBean2PartMap(String writSort, Object javaBean, String[] ignores) {

        if (javaBean == null) {
            return null;
        }
        Map<String, RequestBody> map = new HashMap<>();
        String key = "";
        String value = "";


        HashMap<String, String> testMap = new HashMap<>();


        Method[] caseInfoMethods = javaBean.getClass().getDeclaredMethods();
        for (int i = 0; i < caseInfoMethods.length; i++) {
            if (caseInfoMethods[i].getName().startsWith("get")) {
                key = caseInfoMethods[i].getName().substring(3);
                key=writSort+Character.toLowerCase(key.charAt(0))+key.substring(1);
//                key=Character.toLowerCase(key.charAt(0))+key.substring(1);
                if (key.equals("id")){
                    continue;
                }
                try {
                    value = (String) caseInfoMethods[i].invoke(javaBean, (Object[]) null);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
                //忽略掉不需要的属性
                boolean isIgnore=true;
                for (String s:ignores){
                    if (key.equals(s)){
                        isIgnore=true;
                        break;
                    }else {
                        isIgnore=false;
                    }
                }
                if (isIgnore==false){
//                    map.put(key,value==null?RxPartMapUtils.toRequestBodyOfText(""):RxPartMapUtils.toRequestBodyOfText(value));
//                        map.putString(key,value==null? "fh":"haodeddde");

                    testMap.put(key,value==null?"":value);

                }
            }
        }
        Log.e(TAG,"testMap:"+testMap.toString());
        return map;
    }

*/





    /*
  * 判断是否为整数
  * @param str 传入的字符串
  * @return 是整数返回true,否则返回false
*/


    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }


    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }


    //先上Java代码
    public static String getMD5(String s) {
        char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        try {
            byte[] btInput = s.getBytes("utf-8");
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }




    public static void putTextIntoClip(Context context,String data){
        ClipboardManager clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        //创建ClipData对象
        ClipData clipData = ClipData.newPlainText("label", data);
        //添加ClipData对象到剪切板中
        clipboardManager.setPrimaryClip(clipData);
    }




    public static String bytesToString(ByteString src, String charSet) {
        if(TextUtils.isEmpty(charSet)) {
            charSet = "GB2312";
        }
        return bytesToString(src.toByteArray(), charSet);
    }

    public static String bytesToString(byte[] input, String charSet) {
        ByteBuffer buffer = ByteBuffer.allocate(input.length);
        buffer.put(input);
        buffer.flip();

        Charset charset = null;
        CharsetDecoder decoder = null;
        CharBuffer charBuffer = null;

        try {
            charset = Charset.forName(charSet);
            decoder = charset.newDecoder();
            charBuffer = decoder.decode(buffer.asReadOnlyBuffer());
            return charBuffer.toString();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "error";
    }


}
